<?php
// $Id$

/**
 * Controller_Channel 控制器
 */
class Controller_Channel extends Controller_Abstract
{
	function actionIndex()
	{
		if(null == $this->_app->currentUser())
		{
			return $this->_redirect(url('default/index'));
		}
		$cur_user = $this->_app->currentUserObject();

		$page = intval($this->_context->page);
		if ($page < 1) $page = 1;
		$select = Channel::find()->all();;

		$select->limitPage($page, 10);
		// 将分页信息和查询到的数据传递到视图
		$this->_view['pagination'] = $select->getPagination();
		$this->_view['channels'] = $select->getAll();

		if($select->getCount() > 10)
		{
			$this->_view['num'] = 10;
		}
		else
		{
			$this->_view['num'] = $select->getCount();
		}
		$this->_viewname = 'index';
	}

	function actioninsert()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
		$this->_viewname = 'insert';
	}

	function actionAdd()
	{
		if(null == $this->_app->currentUser())
		{
			return $this->_redirect(url('default/index'));
		}
		$cur_user = $this->_app->currentUserObject();
		
		if(isset($_POST['channelname']))
		{
			$channelnames = $_POST['channelname'];//这里取得POST过来的文本框的数目
			//for($i=1011;$i<=($num+1011);$i++)
			foreach($channelnames as $value)
			{ 
			  if($value != "")
			  {
					$Channel = new Channel();
					$Channel->channel_name = $value;
					$Channel->save();
			  }
			}  
			return $this->_redirectMessage(
						'提示您:',
						'栏目添加成功',
						url('Channel/index'));
		}
	}

	function actionDelete()
	{
		if(null == $this->_app->currentUser())
		{
			return $this->_redirect(url('default/index'));
		}

		$user = $this->_app->currentUserObject();
		//if(3 != $user->permission_id)
		//{
		//	return $this->_redirect(url('Channel/index'));
		//}
        if(isset($_POST['checkboxid'])){
			$id=$_POST['checkboxid'];
			
			foreach ($id as $value){
				//$Channel = Channel::find('channel_id  = ?', $value)->query();
				//$Channel->channel_hide_status=1;
				Channel::meta()->destroyWhere('channel_id = ?', $value);
				//删除栏目相关的文章
			}
		}

		return $this->_redirect(url('Channel/index'));
	}
	
	function actionEdit()
	{
		if(null == $this->_app->currentUser())
		{
			return $this->_redirect(url('default/index'));
		}

		//$cur_user = $this->_app->currentUserObject();
	    $col = Channel::find('channel_id = ?', $this->_context->channel_id)->query();
		
		if($col->id() != $this->_context->channel_id)
		{
		    return $this->_redirect(url('Channel/index'));
		}

        if(isset($_POST['channel_title']))
		{
			$col->channel_name =$_POST['channel_title'];
			$col->channel_desc =$_POST['channel_desc'];
			$col->channel_sequence=$_POST['channel_seqence'];
			if(isset($_POST['channel_hide_or_not']))
			{
			    $col->channel_status=$_POST['channel_hide_or_not'];
			}
			$col->save();
			return $this->_redirectMessage(
					'提示您:',
					'编辑成功',
					url('Channel/index'));
		}

		$this->_view['col'] = $col;
		$this->_viewname = 'edit';
	}

	function actionuploadedimage()
	{
				echo "{";
				echo				"error: '" . $error . "',\n";
				echo				"error_code: '" . $error_code . "',\n";
				echo "}";
				return;
		if(null == $this->_app->currentUser())
		{
			echo "err";
		}
		else
		{
			$error = "";
			$msg = "";
			$error_code=0;
			$fileElementName = 'fileToUpload';
			if(!empty($_FILES[$fileElementName]['error']))
			{
				switch($_FILES[$fileElementName]['error'])
				{
					case '1':
						$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
					    $error_code = 102;
						return;
						break;
					case '2':
						$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
					    $error_code = 102;
						return;
						break;
					case '3':
						$error = 'The uploaded file was only partially uploaded';
					    $error_code = 102;
						return;
						break;
					case '4':
						$error = 'No file was uploaded.';
					    $error_code = 102;
						return;
						break;

					case '6':
						$error = 'Missing a temporary folder';
					    $error_code = 102;
						return;
						break;
					case '7':
						$error = 'Failed to write file to disk';
					    $error_code = 102;
						return;
						break;
					case '8':
						$error = 'File upload stopped by extension';
					    $error_code = 102;
						return;
						break;
					case '999':
					default:
						$error = 'No error code avaiable';
				}
			}
			elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
			{
				$error_code=102;
			}
			else 
			{
					$msg .= " File Name: " . $_FILES['fileToUpload']['name'] . ", ";
					$msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']);
			}		
			if($error_code == 102)
			{
				echo "{";
				echo				"error: '" . $error . "',\n";
				echo				"error_code: '" . $error_code . "',\n";
				echo "}";
				return;
			}
			
			$col = Channel::find('channel_id = ?', $this->_context->channel_id)->query();
			
			if($col->id() != $this->_context->channel_id)
			{
				return $this->_redirect(url('Channel/index'));
			}

			$time = time();
			$uploader = new Helper_Uploader();
			$file = $uploader->file($fileElementName);
			if($file->isSuccessed())
			{
			try{
					if($file->isValid('jpg, jpeg, png, gif'))
					{
						$filepath = $this->_app->config('ROOT_DIR'). '/img/channel_log/' . date('Ym');
						//echo "file:".$filepath;
						$url_path = $this->_context->baseDir(). 'img/channel_log/' . date('Ym');
						
						if(!file_exists($filepath))
						{
							mkdir($filepath);
						}
						if(file_exists($filepath.'/'.$time.$file->filename()))
						{
							unlink ( $filepath.'/'.$time.$file->filename() );
						}
						//$file->move($filepath.'/'.$time.$file->filename());
						//$dst_file = Helper_Upload::makethumb($filepath.'/'.$time.$file->filename(), 48, 48, 64, 64);
						//$dst_url_path = $url_path.'/'.$time.$file->filename().'.thumb.jpg';
						
						$image = Helper_Image::createFromFile($file->filepath(), $file->extname());
						$w = Q::ini('appini/enter_log_width');
						$h = Q::ini('appini/enter_log_height');

						$image->crop($w, $h);
						$image->saveAsJpeg($filepath.'/'.$time.$file->filename());
						$dst_file = $filepath.'/'.$time.$file->filename();
						
						$image->destroy();
						$file->unlink();

						if(strlen($col->channel_logo ) > 0)
						{							
							if(file_exists($col->channel_logo ))
							{
								//echo "avatar_url:".$user->avatar_url;
								unlink($col->channel_logo  );
							}
						}
						if(strlen($dst_file) > 0 && file_exists($dst_file))
						{	
							//echo "dst_file:".$dst_file;
							$col->channel_logo  = $url_path.'/'.$time.$file->filename();
						}
						else
						{
							$col->channel_logo  = null;
						}
						$col->save();
					    $error_code = 100;
						
						$retVal = "{success:'".$enterprise->channel_logo ."'}";

						return $retVal;
					}
					else 
					{
						$error='uploaded err';
					    $error_code = 105;
					}
				}
				catch (Exception $ex)
				{				
						$error='uploaded err';
					    $error_code = 102;
				}
				return;
			}
			echo "{";
			echo				"error: '" . $error . "',\n";
			echo				"error_code: '" . $error_code . "',\n";
			echo "}";

		}
	}

	function actionRequire()
	{
		require 'genrss.php';
		
		$web_site=Q::ini('appini/web_site_ip');
		$rss_gen=new RSS('test', "http://www.baidu.com", '电信动态', '');
		if(!isset($this->_context->channel_id))
		{
		    $rss_gen=new RSS('test', "http://www.baidu.com", '电信动态', '');
			$date = Date('Y-m-d H:i:s', time()); 
			$rss_gen->AddItem("我和你", 
				"http://www.baidu.com", "你需要什么", $date, $web_site.$this->_context->baseDir().'static/test/00.jpg');
			$rss_gen->AddItem("我和你", 
				"http://www.baidu.com", "你需要什么", $date, $web_site.$this->_context->baseDir().'static/test/00.jpg');
			$ret=$rss_gen->Fetch();
			echo $ret;
			return;
		}
		else
		{
			$channel = Channel::find('channel_id = ?', $this->_context->channel_id)->query();;


            $page = intval($this->_context->page);
			if ($page < 1) $page = 1;

            $select = CommonArticle::find('channel_id = ?', $this->_context->channel_id)->order('article_id DESC')->all();
			$select->limitPage($page, Q::ini('appini/web_page_count'));
            
            $articles = $select->getAll();

		    $rss_gen=new RSS($channel->channel_name, "http://www.baidu.com", $select->getCount(), '');
            $date = Date('Y-m-d H:i:s', time()); 
			foreach($articles as $artic)
			{
				if(strlen($artic->article_icon) > 0)
				{
				    $rss_gen->AddItem($artic->article_name, 
					    $web_site.$this->_context->baseDir().$artic->article_url, $artic->article_summary, $date, $artic->article_icon);
				}
				else
				{
                    $summery = "...";
                    if(strlen($artic->article_summary) > 0)
                    {
                        $summery = $artic->article_summary ;
                    }
					$ran = (rand())%7;
				    $rss_gen->AddItem($artic->article_name, 
					    $web_site.$this->_context->baseDir().$artic->article_url, $summery, $date, $web_site.$this->_context->baseDir()."static/test/$ran.jpg");
				}
			}
			$ret=$rss_gen->Fetch();
			echo $ret;
			return;
		}
	}	
	
	function actionRequireAllChannel()
	{
		require 'genrss.php';
		if(null == $this->_app->currentUser())
		{
			return $this->_redirect(url('default/index'));
		}

		$cur_user = $this->_app->currentUserObject();
		$rss_gen=new RSS('电信', "http://www.baidu.com", '测试数据这里', '');

		$date = Date('Y-m-d H:i:s', time()); 
		$Channels = Channel::find('enterprise_id = ?', $cur_user->enterprise_id)->getAll();
		$web_site=Q::ini('appini/web_site_ip');
		foreach($Channels as $col)
		{
			//$channel_site = $web_site;
			//$channel_site .= 'index.php?controller=Channel&amp;action=require&amp;channel_id='.$col->channel_id;
			$channel_id=$col->channel_id;
			$rss_gen->AddItem($col->channel_name, $channel_id, 'null', $date, 'null');
		}
		return $rss_gen->Display();
	}
}
